<?php

namespace backend\controllers;

use backend\models\AdminUser;
use Yii;
use yii\data\Pagination;
use backend\models\AdminRoleUser;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\widgets\LinkPager;
/**
 * AdminUserRoleController implements the CRUD actions for SystemRoleUser model.
 */
class AdminUserRoleController extends BaseController
{
	public $layout = "lte_main";

    /**
     * Lists all SystemRoleUser models.
     * @return mixed
     */
    public function actionIndex()
    {

        $model = new AdminRoleUser();
        list($querys,$models, $pages, $totalCount, $startNum, $endNum) = $this->getList();
        if (Yii::$app->request->isAjax == true) {
            $result = ['models'=>$models, 'pages'=>$pages, 'totalNum'=>$totalCount,
            'startNum'=>$startNum,'endNum'=>$endNum];
            return $this->asJson(['errno'=>0, 'data'=>$result]);
        }
        else{
            return $this->render('index', [
            'query'=>json_encode($querys),
            'modelLabel'=>json_encode($model->attributeLabels()),
            'models'=>json_encode($models), 'pages'=>$pages, 'totalNum'=>$totalCount,
            'startNum'=>$startNum,
            'endNum'=>$endNum,
            'role_id'=> empty($querys['role_id']) == false ? $querys['role_id'] : ''
            ]);
        }
    }


    private function getList(){
        $query = AdminRoleUser::find();
//        $query->joinWith(['system_user user'])

        $querys = Yii::$app->request->get('query');
        if(empty($querys)== false && count($querys) > 0){
            $condition = "";
            $parame = array();
            foreach($querys as $key=>$value){
                $value = trim($value);
                if(empty($value) == false){
                    $parame[":{$key}"]=$value;
                    if(empty($condition) == true){
                        $condition = " {$key}=:{$key} ";
                    }
                    else{
                        $condition = $condition . " AND {$key}=:{$key} ";
                    }
                }
            }
            if(count($parame) > 0){
                $query = $query->where($condition, $parame);
            }
        }
        $totalCount = $query->count();
        $query = $query
            ->select(['system_role_user.*','user.uname as user_name','role.name as role_name'])
            ->leftJoin('system_user user', 'user_id = user.id')
            ->leftJoin('system_role as role', 'role_id = role.id');
        $pagination = new Pagination([
            'totalCount' =>$totalCount,
            'pageSize' => '10',
            'pageParam'=>'page',
            'pageSizeParam'=>'per-page']
        );
        $pages = LinkPager::widget([
            'pagination' => $pagination,
            'nextPageLabel' => '»',
            'prevPageLabel' => '«',
            'firstPageLabel' => '首页',
            'lastPageLabel' => '尾页',
        ]);
        $pages = str_replace("\n", '', $pages);
        $orderby = Yii::$app->request->get('orderby', ' id asc ');
        if(empty($orderby) == false){
            $query = $query->orderBy($orderby);
        }
        $models = $query
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->asArray()
            ->all();
        $startNum = $pagination->getPage() * $pagination->getPageSize() + 1;
        $endNum = ($pagination->getPage() + 1) * $pagination->getPageSize();
        $endNum = $endNum < $totalCount ?  $endNum : $totalCount;
        return [$querys,$models, $pages, $totalCount,$startNum,$endNum];
    }


    /**
     * Displays a single SystemRoleUser model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $data = $model->getAttributes();
        
        
        return $this->asJson($data);

    }

    /**
     * Creates a new SystemRoleUser model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $role_id = Yii::$app->request->post('role_id', '');
        $user_name = Yii::$app->request->post('user_name', '');
        $user = AdminUser::findOne(['uname'=>$user_name]);

        if (empty($user) == false) {
            $role_user = AdminRoleUser::findOne(['user_id'=>$user->id,'role_id'=>$role_id]);
            if(empty($role_user) == true){
                $model = new AdminRoleUser();
                $model->user_id = $user->id;
                $model->role_id = $role_id;
                $model->create_user = Yii::$app->user->identity->uname;
                $model->create_date = date('Y-m-d H:i:s');
                $model->update_user = Yii::$app->user->identity->uname;
                $model->update_date = date('Y-m-d H:i:s');
                if($model->validate() == true && $model->save()){
                    $msg = array('errno'=>0, 'msg'=>'保存成功');
                    return $this->asJson($msg);
                }
                else{
                    $msg = array('errno'=>2, 'data'=>$model->getErrors());
                    return $this->asJson($msg);
                }
            }
            else{
                $msg = array('errno'=>1, 'msg'=>'用户已经存在！');
                return $this->asJson($msg);
            }
        } else {
            $msg = array('errno'=>2, 'msg'=>'用户不存在！');
            return $this->asJson($msg);
        }
    }

    /**
     * Updates an existing SystemRoleUser model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate()
    {
        $id = Yii::$app->request->post('id');
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())) {
        
              $model->update_user = Yii::$app->user->identity->uname;
              $model->update_date = date('Y-m-d H:i:s');            if($model->validate() == true && $model->save()){
                $msg = array('errno'=>0, 'msg'=>'保存成功');
                return $this->asJson($msg);
            }
            else{
                $msg = array('errno'=>2, 'data'=>$model->getErrors());
                return $this->asJson($msg);
            }
        } else {
            $msg = array('errno'=>2, 'msg'=>'数据出错');
            return $this->asJson($msg);
        }
    
    }

    /**
     * Deletes an existing SystemRoleUser model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete(array $ids)
    {
        if(count($ids) > 0){
            $c = AdminRoleUser::deleteAll(['in', 'id', $ids]);
            return $this->asJson(array('errno'=>0, 'data'=>$c, 'msg'=>json_encode($ids)));
        }
        else{
            return $this->asJson(array('errno'=>2, 'msg'=>''));
        }
    }

	
	 

    /**
     * Finds the SystemRoleUser model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return AdminRoleUser the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = AdminRoleUser::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
